package com.company.project.search.engine;

import com.alibaba.fastjson.JSONArray;
import com.company.project.search.entity.Search;
import com.company.project.search.util.OkHttpUtil;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * art1lib
 * https://art1lib.com
 */

public final class E3 extends AbstractE implements Callback {

    private static final String host = "https://art1lib.com";
    private static final String url = "https://art1lib.com/s/";


    @Override
    public JSONArray provideCategory() {
        JSONArray list = new JSONArray();
        list.add(new Category("3-1", "ArtLib-Book"));
        list.add(new Category("3-0", "ArtLib-Other"));
        return list;
    }

    private static final Headers headers = new Headers.Builder()
            .add("Referer", "https://art1lib.com")
            .add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
            .add("Content-Type", "application/x-www-form-urlencoded")
            .add("Cache-Control", "no-cache")
            .add("sec-fetch-dest", "document")
            .add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36")
            .build();

    @Override
    public void search(Param p) {
        p.engine = Engine.ID_E3;
        Request request = new Request.Builder()
                .url(String.format("%s%s?", url, p.keyword))
                .get()
                .headers(headers)
                .tag(p)
                .build();
        OkHttpUtil.getInstance().enqueue(request, this);
    }

    private void parse(Document html, Result result) {
        Elements items = html.getElementsByClass("bookRow");
        if (items.isEmpty()) return;
        Result.Header header = new Result.Header();
        header.engine = Engine.ID_E3;
        header.engineName = "ArtLib";
        header.maxPage = 0;
        header.totalCount = 0;
        result.headers = new HashSet<>();
        result.headers.add(header);
        Element j;
        List<Search> list = new ArrayList<>();
        String name;
        for (Element i : items) {
            j = i.getElementsByClass("z-book-none-cover").first();
            name = j.attr("data-title");
            Search search = Search.newInstance(Engine.ID_E3);
            search.setName(name.length() > 200 ? name.substring(0, 150) : name);
            search.setAuthor(j.attr("data-author"));
            search.setUrl(host + j.getElementsByTag("a").first().attr("href"));
            search.setCategory("3-1");
            search.setSource("ArtLib");
            String pubDate = i.getElementsByClass("bookProperty").first().getElementsByClass("property_value").text();
            search.setPublishDate(pubDate == null ? "无" : pubDate.length() > 20 ? pubDate.substring(0, 10) : pubDate);
            list.add(search);
        }
        result.list = list;
        if (callback != null) callback.callback(result);
    }

    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        System.out.println("E3响应失败");
        // 404 400
    }

    @Override
    public void onResponse(@NotNull Call call, Response response) throws IOException {
        if (response.isSuccessful()) { // 200
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String json = responseBody.string();
                Document html = Jsoup.parse(json);
                Param p = (Param) call.request().tag();

                if (p != null) System.out.println("E3响应成功:" + (System.currentTimeMillis() - p.duration) + "ms");
                Result result = new Result(p);
                parse(html, result);
            }
        }
    }

    private static final class Holder {
        private static final AbstractE ins = new E3();
    }

    private E3() {

    }

    public static AbstractE getInstance() {
        return Holder.ins;
    }
}
